package com.wq.jdk8;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: wangqiang20995
 * @Date:2019/7/11
 * @Description:
 * @Resource:
 */
public class HashMapResizeDemo {

    public static void main(String[] args) {
        bitForHashCode();
        Map<InnerKey,String> map = new HashMap<>(4);

        map.put(new InnerKey("assdf"),"one");
        map.put(new InnerKey("dddcs"),"two");
        map.put(new InnerKey("fdbui"),"four");
        map.put(new InnerKey("ewhiq"),"five");
        map.put(new InnerKey("weiru"),"three");

        System.out.println(map);
    }

    private static void bitForHashCode() {
        InnerKey innerKey = new InnerKey("3450");
        innerKey.setKey("hello123");
        int hashCode = innerKey.hashCode();
        System.out.println("hashcode:" + hashCode);
        System.out.println(Integer.toBinaryString(innerKey.hashCode()));
        //假设Map的长度为16,那么对应的index通常是hashcode & (length -1)
        System.out.println("index for map:" + (innerKey.hashCode() & (15)));

        //int的高16位
        int num = hashCode >>> 16;
        System.out.println("hashcode >>> 16 = " + Integer.toBinaryString(num));
        num = hashCode ^ num;
        System.out.println("异或结果:" + Integer.toBinaryString(num));

        //最后的下标
        System.out.println("finally index:" + Integer.toBinaryString(num & (15)));
    }
}

class InnerKey {
    private String key;

    public InnerKey(String key){
        this.key = key;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof InnerKey)) return false;
        InnerKey innerKey = (InnerKey) o;
        return Objects.equals(getKey(), innerKey.getKey());
    }

    @Override
    public int hashCode() {

        return Objects.hash(getKey());
    }

    @Override
    public String toString() {
        return "InnerKey{" +
                "key='" + key + '\'' +
                '}';
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}